package com.cloudansys.core.util;

import com.alibaba.fastjson.JSONObject;
import com.cloudansys.config.DefaultConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DingTalkUtil {

    private static OkHttpClient mClient;

    //初始化客户端
    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10L, TimeUnit.SECONDS);
        builder.readTimeout(10L, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(200);
        dispatcher.setMaxRequests(200);
        builder.dispatcher(dispatcher);
        mClient = builder.build();
    }

    /**
     * 通用 POST 请求方法  依赖 OKhttp3
     * @param message 所要发送的消息
     * @return 发送状态回执
     */
    public static String postWithJson(String message) {
        String project = DefaultConfig.getProject();
        String url = null;
        try {
            url = DefaultConfig.getSign();
        } catch (Exception e) {
            log.error("获取签名失败！【DingTalkUtil】");
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        //固定参数
        jsonObject.put("msgtype", "text");
        JSONObject content = new JSONObject();
        //此处message是你想要发送到钉钉的信息
        content.put("content", project + "\r" + message);
        jsonObject.put("text", content);
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        assert url != null;
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = mClient.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.string();
            }
        } catch (IOException e) {
            log.error("消息发送失败！【DingTalkUtil】");
            e.printStackTrace();
        }
        return null;
    }

}
